import { Controller } from 'egg';

export default class ConsulController extends Controller {
  public async healthCheck() {
    const { ctx } = this;
    ctx.body = '200';
  }

  public async register() {
    const { ctx, app } = this;

    try {
      ctx.logger.info('get consul register request from', ctx.ip);
      app.messenger.sendToAgent('consul_register', ctx.ip);

      ctx.setMessage('广播consul注册到agent成功');
      ctx.sendSuccess();
    } catch (e) {
      ctx.logger.error('consul 注册失败', e);

      ctx.body = 'consul 注册失败';
    }
  }

  public async deregister() {
    const { ctx, app } = this;

    try {
      ctx.logger.info('get consul deregister request from', ctx.ip);
      app.messenger.sendToAgent('consul_deregister', ctx.ip);

      ctx.setMessage('广播consul取消注册到agent成功');
      ctx.sendSuccess();
    } catch (e) {
      ctx.logger.error('consul 取消注册失败', e);

      ctx.body = 'consul 取消注册失败';
    }
  }
}
